#include "controller.h"

double tmpConst = 50.0;

Controller::Controller ( MainWindow * mainWindow )
: mainWindow ( mainWindow )
{
    Point2D p1 ( 9.0, 9.0 );
    Point2D p2 ( 10.0, 10.0 );
    Point2D p3 ( 11.0, 11.0 );

    Point2D v1 ( 0.0, 0.000002 );
    Point2D v2 ( 0.0, -0.000002 );
    Point2D v3 ( 0.0, 0.00000 );

    double r1 = 10.0, r2 = 10.0, r3 = 10.0;
    double m1 = 10.0, m2 = 10.0, m3 = 10.0;
    model.SetTimeInterval ( 0.2 );

    qsrand ( QTime::currentTime().msec());

    const double drawRad = 10.0;
    const double mass = 10.0;
    const double maxRadius = 3.0;
    const double bodyNum = 100;
    const Point2D center ( 10.0, 10.0 );

    model.AddBody ( p1, r1, m1, v1 );
    model.AddBody ( p2, r2, m2, v2 );
    mainWindow -> AddCircle ( p1.x * tmpConst, p1.y * tmpConst, drawRad, Qt::blue );
    mainWindow -> AddCircle ( p2.x * tmpConst, p2.y * tmpConst, drawRad, Qt::blue );

    /*
    for ( int i = 0; i < bodyNum; ++i )
    {
        Point2D p ( center.x - maxRadius + Rand() * 2 * maxRadius, center.y - maxRadius + Rand() * 2 * maxRadius );
        Point2D v ( 0.0, 0.0 );
        model.AddBody ( p, drawRad, mass, v );
        mainWindow -> AddCircle ( p1.x * tmpConst, p1.y * tmpConst, drawRad, Qt::blue );
    }
    */
    /*
    const int circleNum = 20;
    const int bodyPerCircleBase = 10;
    for ( int i = 0; i < circleNum; ++i )
    {
        double rad = i * maxRadius / (double) ( circleNum - 1 );
        int bodyNum = bodyPerCircleBase * rad;
        for ( int j = 0; j < bodyNum; ++j )
        {
            double alpha = j * 2 * PI / bodyNum;
            Point2D p ( center.x + rad * cos ( alpha ), center.y + rad * sin ( alpha ));
            Point2D v ( 0.0, 0.0 );
            model.AddBody ( p, drawRad, mass, v );
            mainWindow -> AddCircle ( p.x * tmpConst, p.y * tmpConst, drawRad, QColor ( Rand() * 255, Rand() * 255, Rand() * 255 ) );
            //mainWindow -> AddCircle ( p.x * tmpConst, p.y * tmpConst, drawRad, Qt::blue );
        }
    }
    */
    //Point2D p ( center.x + 5.0, center.y );
    //Point2D v ( 0.0, 0.0 );
    //model.AddBody ( p, drawRad, 10 * mass, v );
    //mainWindow -> AddCircle ( p.x * tmpConst, p.y * tmpConst, 2 * drawRad, Qt::black );
}

void Controller::run()
{
    stopFlag = false;
    //QVector<Point2D> vectData1;
    //QVector<Point2D> vectData2;
    while ( ! stopFlag )
    {
        model.CalcStep();

        for ( int i = 0; i < model.GetBodyCount(); ++i )
        {
            Point2D pos;
            model.GetBodyPos( i, pos );
            mainWindow -> MoveCircle ( i, pos.x * tmpConst, pos.y * tmpConst );
        }

        mainWindow -> SetMassCenter ( model.GetMassCenter() * tmpConst );
    }
    //SavePointVector ( "debug1.txt", vectData1 );
    //SavePointVector ( "debug2.txt", vectData2 );
}

void Controller::Stop()
{
    this -> stopFlag = true;
}
